package com.luoran.bartalks.api;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.luoran.bartalks.core.AppUser;
import com.luoran.bartalks.entity.biz.BtPackingList;
import com.luoran.bartalks.entity.biz.BtPackingListMateriel;
import com.luoran.bartalks.entity.biz.BtPlanDetails;
import com.luoran.bartalks.entity.biz.BtPlanEntry;
import com.luoran.bartalks.entity.biz.BtProject;
import com.luoran.bartalks.entity.biz.BtProjectMember;
import com.luoran.bartalks.service.IBtPackingListMaterielService;
import com.luoran.bartalks.service.IBtPackingListService;
import com.luoran.bartalks.service.IBtPlanBizService;
import com.luoran.bartalks.service.IBtPlanDetailsService;
import com.luoran.bartalks.service.IBtPlanEntryService;
import com.luoran.bartalks.service.IBtProjectMemberService;
import com.luoran.bartalks.service.IBtProjectService;

@RestController
@RequestMapping("/api/project")
public class ProjectApi {

	@Autowired
	private IBtProjectService projectService;

	@Autowired
	private IBtProjectMemberService projectMemberService;

	@Autowired
	private IBtPlanDetailsService planDetailsService;

	@Autowired
	private IBtPlanEntryService planEntryService;

	@Autowired
	private IBtPackingListService packingListService;

	@Autowired
	private IBtPackingListMaterielService packingListMaterielService;

	@Autowired
	private IBtPlanBizService planBizService;

	private static final Logger log = LoggerFactory.getLogger(ProjectApi.class);

	/**
	 * 根据位置id查询用户可操作的项目计划信息
	 * 
	 * @param addressId
	 * @return 返回值格式{state:true/false,msg:成功是空,失败提示信息,data:返回的数据}
	 */
	@RequestMapping("my")
	public String myProjects(String addressId) {
		JSONObject res = new JSONObject();
		String companyId = AppUser.get().getCompanyId();
		// 根据当前登录用户ID获取当前用户所属的项目.
		String memberId = AppUser.get().getId();
		// 获取项目成员关系集合
		List<BtProjectMember> projectMembers = projectMemberService.getProjectMembersByMemberId(memberId, companyId);
		// 获取项目ID集合
		List<String> projectIds = new ArrayList<>();
		for (BtProjectMember projectMember : projectMembers) {
			if (!projectIds.contains(projectMember.getProjectId())) {
				projectIds.add(projectMember.getProjectId());
			}
		}
		log.info("根据用户ID获取到的项目ID集合>>[{}]", projectIds);
		JSONArray projects = new JSONArray();
		// 遍历项目id集合
		for (String projectId : projectIds) {// 遍历项目
			JSONObject projectObj = new JSONObject();// 封装每个项目对象
			// 根据项目id 查询项目详情.
			BtProject prosistentProject = projectService.getProjectInfo(projectId);
			projectObj.put("projectName", prosistentProject.getProjectName());// 项目名称
			projectObj.put("projectId", projectId);// 项目id
			// 该项目的计划列表
			JSONArray plans = new JSONArray();
			log.info("获取当前项目名称为[{}]的所属计划>>", prosistentProject.getProjectName());
			// 通过每一个项目id.获取该项目包含的所有计划
			List<BtPlanDetails> prosistentPlans = planDetailsService.findPlanByProjectId(projectId);
			log.info("[{}]项目的所属计划有[{}]条<<", prosistentProject.getProjectName(), prosistentPlans.size());
			for (BtPlanDetails prosistentPlan : prosistentPlans) {// 遍历计划
				log.info("***[{}]的计划描述[{}]***", prosistentPlan.getPlanCode(), prosistentPlan.getRemark());
				JSONObject planObj = new JSONObject();// 封装每一个计划对象
				planObj.put("planId", prosistentPlan.getId());// 计划id
				planObj.put("planCode", prosistentPlan.getPlanCode());// 计划编码
				planObj.put("desc", prosistentPlan.getRemark());// 计划描述
				planObj.put("startDate", date2Str(prosistentPlan.getStartDate()));// 开始日期
				planObj.put("endDate", date2Str(prosistentPlan.getEndDate()));// 结束日期
				/**
				 * 需要通过位置ID判断该位置是起始点,还是途径点. 如果是起点,需要查询该计划的所有箱单,确定应装物料的总和.起点无需卸货
				 * 如果是途径点,那么需要查询上一地点实际装货的总和.作为该地点的应卸物料的总和. 如果是终点,终点无需装货.只需卸货
				 */
				// 通过计划id获取.计划途径点集合.
				List<BtPlanEntry> planEntrys = planEntryService.getPlanEntryByPlanId(prosistentPlan.getId(), companyId);
				List<String> positions = new ArrayList<>();// 当前计划途径点位置id的集合
				for (BtPlanEntry planEntry : planEntrys) {
					positions.add(planEntry.getAddressId());
				}
				int endPlaceSign = planEntrys.size();// 终点位置的sign值
				if (positions.contains(addressId)) {// 该地点属于该计划
					// 根据位置id,查询途径点是起点?终点?中途点?
					BtPlanEntry prosistentPlanEntry = planEntryService
							.getPlanEntryByPlanIdAndAddresId(prosistentPlan.getId(), addressId, companyId);
					String planPositionId = prosistentPlanEntry.getId();// 途径点记录ID
					if (prosistentPlanEntry.getSign() == 1) {// 当前地点是起点.
						log.info("当前位置[{}]是起始地<<", prosistentPlanEntry.getAddressName());
						// 获取应装数量.需要查询该计划的箱单
						List<BtPackingList> packingLists = packingListService
								.findPackingListByPlanId(prosistentPlan.getId());
						int materielAmount = 0;
						for (BtPackingList prosistentPackingList : packingLists) {
							// 根据箱单查询箱单物料关系计算出物料数量
							log.info("箱单编码为[{}]", prosistentPackingList.getPackingListCode());
							List<BtPackingListMateriel> packingListMateriels = packingListMaterielService
									.getMaterielsByPackingListId(prosistentPackingList.getId());
							for (BtPackingListMateriel packingListMateriel : packingListMateriels) {
								// 物料数量.
								materielAmount += packingListMateriel.getMaterielAmount();
							}
						}
						planObj.put("needIn", materielAmount);// 应装
						// 根据计划位置关系id.计划id.项目id.查询记录表 获取已装数量.
						int count = planBizService.getInedItemCount(planPositionId, prosistentPlan.getId(), projectId);
						planObj.put("ined", count);// 已装
						planObj.put("needOut", 0);// 应卸
						planObj.put("outed", 0);// 已卸
						planObj.put("planPositionId", planPositionId);// 计划途径点记录Id
						// 按钮显示标识
						planObj.put("loadingBtnShow", true);
						planObj.put("unloadBtnShow", false);
						plans.add(planObj);
					} else if (prosistentPlanEntry.getSign() == endPlaceSign) {// 当前地点是终点
						log.info("当前位置[{}]是目的地<<", prosistentPlanEntry.getAddressName());
						planObj.put("needIn", 0);// 应装
						planObj.put("ined", 0);// 已装
						// 获取应卸,已卸.
						// 应卸.即上一地点已装.需要获取上一地点已装记录.
						int lastSign = prosistentPlanEntry.getSign() - 1;// 获取上一地点的sign
						BtPlanEntry lastPlanEntry = planEntryService.getPlanEntryByPlanIdAndSign(prosistentPlan.getId(),
								companyId, lastSign);// 根据planId,sign,查询计划途径点
						// 查询上一地点已装
						int lastIned = planBizService.getInedItemCount(lastPlanEntry.getId(), prosistentPlan.getId(),
								projectId);
						planObj.put("needOut", lastIned);// 应卸
						// 已卸.查询记录表
						int outed = planBizService.getOutedItemCount(prosistentPlanEntry.getId(),
								prosistentPlan.getId(), projectId);
						planObj.put("outed", outed);// 已卸
						planObj.put("planPositionId", planPositionId);// 计划途径点记录Id
						// 按钮显示标识
						planObj.put("loadingBtnShow", false);
						planObj.put("unloadBtnShow", true);
						plans.add(planObj);
					} else {// 当前地点是中途点
						log.info("当前位置是中途点[{}]<<", prosistentPlanEntry.getAddressName());
						// 应卸.即上一地点已装.需要获取上一地点已装记录.
						int lastSign = prosistentPlanEntry.getSign() - 1;// 获取上一地点的sign
						BtPlanEntry lastPlanEntry = planEntryService.getPlanEntryByPlanIdAndSign(prosistentPlan.getId(),
								companyId, lastSign);// 根据planId,sign,查询计划途径点
						// 查询上一地点已装,
						int lastIned = planBizService.getInedItemCount(lastPlanEntry.getId(), prosistentPlan.getId(),
								projectId);
						planObj.put("needOut", lastIned);// 应卸
						// 已卸.查询记录表已卸记录
						int outed = planBizService.getOutedItemCount(prosistentPlanEntry.getId(),
								prosistentPlan.getId(), projectId);
						planObj.put("outed", outed);
						// 应装.查询记录表已卸记录.
						planObj.put("needIn", outed);
						// 已装.查询记录表已装记录
						int ined = planBizService.getInedItemCount(prosistentPlanEntry.getId(), prosistentPlan.getId(),
								projectId);
						planObj.put("ined", ined);
						planObj.put("planPositionId", planPositionId);// 计划途径点记录Id
						// 按钮显示标识
						planObj.put("loadingBtnShow", true);
						planObj.put("unloadBtnShow", true);
						plans.add(planObj);
					}
				}
			}
			if (plans.isEmpty()) {// 如果没有计划则不添加该项目
				continue;
			}
			projectObj.put("plans", plans);
			projects.add(projectObj);
		}
		res.put("state", true);
		res.put("data", projects);
		return res.toJSONString();
	}

	// 日期格式化
	public String date2Str(Date date) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		return sdf.format(date);
	}

}
